package com.serverclient.jdk.invacation;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

import com.serverclient.jdk.annotation.HttpMethod;
import com.serverclient.jdk.annotation.HttpServer;
import com.serverclient.utility.HttpUtility;

public class HttpInvocationHandler implements InvocationHandler{
	/**
	 * 拦截调用端调用的方法，并进行接口调用，然后将接口调用结果当做被拦截的方法的返回结果
	 * 第一个参数为生成的代理对象
	 * 第二个参数为被拦截的方法
	 * 第三个参数为调用被拦截方法传递的参数
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		HttpMethod httpMethod = method.getAnnotation(HttpMethod.class);
		if(httpMethod != null){
			int port = httpMethod.port();
			StringBuilder serverUrl = new StringBuilder();
			serverUrl.append(httpMethod.scheme().scheme);
			serverUrl.append(httpMethod.server());
			//http的80端口和https的443端口不拼接在链接中
			if((HttpServer.Scheme.HTTP.equals(httpMethod.scheme()) && port != 80) 
					|| (HttpServer.Scheme.HTTPS.equals(httpMethod.scheme()) && port != 443)) {
				serverUrl.append(":");
				serverUrl.append(httpMethod.port());
			}
			serverUrl.append(httpMethod.uri());
			
			if(HttpServer.Method.GET.equals(httpMethod.method())) {
				return HttpUtility.get(serverUrl.toString(),((Map<String,String>)args[0]), ((Map<String,String>)args[1]));
			}else {
				return HttpUtility.post(serverUrl.toString(), args[0], ((Map<String,String>)args[1]));
			}
		}
		throw new RuntimeException(method.getName() + "未找到指定的HttpMethod注解");
	}
}